var o = {}; //所有form元素
var b = new Array(); //复选框元素
var splice = "@@HZFI@@";
var pass = true;
try{
	//select插件初始化配置
	$('.fold-select').anselcfg({});
	//日期插件初始化配置calendar
    $('#penaltyenddate').mobiscroll().calendar({
        theme: 'ios',
        lang: 'zh',
	    display: 'bottom',
	    dateFormat: 'yy-mm-dd'
    });
}catch(e){
	console.log("插件");
}


(function() {
	var requiredArr = $('#bl-wrapper').find('.fold[required]');
	for(var i = 0; i < requiredArr.length; i++) {
		$(requiredArr[i]).find('.label').append('<span class="required">&nbsp;*</span>');
	}
	
	$(".datepicker").each(function (index, element) {
	    var thisPicker = $(this);
	    $(this).mobiscroll().calendar({
	        theme: 'ios',
	        lang: 'zh',
		    display: 'bottom',
		    dateFormat: 'yy-mm-dd'
	    });
	});
})();

function checkDate(form) {
	var form = $("#"+form);
	var flag = true;
	o = {};
	b = new Array();
	$(form).find('input,textarea,select').each(function(index) {
		var _id = $(this).attr('id');
		var _name = $(this).attr('name');
		var _type = $(this).attr('type');
		console.log(index + " " + _id);
		if(_type == 'button' || _type == 'hidden') {
			return true;
		} else if(_type == 'checkbox') {
			if(!_.contains(b, _name))
				b.push(_name);
			return true;
		}
		var _required = $(this).data('required');
		var _minlength = $(this).attr('minlength');
		var _maxlength = $(this).attr('maxlength');
		var _desc = $(this).data('msg');
		var _val = "";
		if(_type == 'radio') {
			if($(this).is(":checked")) {
				_val = $(this).val();
				if(_name)
					o[_name] = _val;
			}
		} else {
			_val = $(this).val();
			if(_name)
				o[_name] = _val;
		}
		//必填校验
		if(_required || "true" == _required || "required" == _required) {
			if(!_val) {
				showAlert("请输入"+_desc);
				flag = false;
				return false;
			}
		}
		if(_minlength && _maxlength && _maxlength != "" && _maxlength == _minlength && _val.length != parseInt(_minlength)) {
			showAlert(_desc + "长度应为" + _minlength);
			flag = false;
			return false;
		} else if(_minlength && _val.length < parseInt(_minlength)) {
			showAlert(_desc + "最小长度为" + _minlength);
			flag = false;
			return false;
		} else if(_maxlength && _val.length > parseInt(_maxlength)) {
			showAlert(_desc + "最大长度为" + _maxlength);
			flag = false;
			return false;
		}

	});
	//复选框处理
	for(var i = 0; i < b.length; i++) {
		var _vals = "";
		var _required = "";
		var _desc = "";
		$("input[name='" + b[i] + "']").each(function() {
			var _name = $(this).attr('name');
			var tmp = $(this).attr('required');
			_desc = $(this).attr('desc');
			if("true" == tmp || tmp) {
				_required = tmp;
			}
			if($(this).is(':checked')) {
				if(_vals) {
					_vals = _vals + splice + $(this).val() || '';
				} else {
					_vals = $(this).val() || '';
				}
			}
		});
		//必填校验
		if(_required || "true" == _required || "required" == _required) {
			if(!_vals) {
				showAlert("请输入"+_desc);
				flag = false;
			}
		}
		o[b[i]] = _vals;
	}
	return flag;
}

function submitForm(form) {
	if(checkDate(form)) {
		if(!$.isEmptyObject(o)){
			var flag = false;
			for(i in o){
				if(o[i]!=""){
					flag = true;
					break;
				}
			}
			if(!flag){
				showAlert("请正确输入信息");
				return false;
			}
		} else {
			showAlert("请正确输入信息");
			return false;
		}
		//提交表单，构造json数据提交到后台
		$.ajax({
			url: initOptions.webSite + $('#'+form).attr("action"),
			data: JSON.stringify(o),
			type: 'post',
			cache: false,
			contentType: 'application/json; charset=UTF-8',
			async: false,
			xhrFields: {
	            withCredentials: true
	       	},
	        crossDomain: true,
			success: function(response) {
				if(response.errorCode == 1) { //正常
					if($('#displayType').val()) {
						sessionStorage.setItem($("#storeKey").val(), response.data);
						window.location.href = $("#resultPage").val();
					} else {
						showAlert("请求成功");
					}
				} else {
					showAlert(response.respDesc ? response.respDesc : "请求失败");
				}
			},
			beforeSend:function(XHR){
	        	showLoader();
		    },
		    complete:function(XHR, TS){
	            hideLoader();
	        }
		});
	}
}

function showAlert(msg, timeout) {
	var $popup;
	if($("#showmsg").length == 0) {
		var showmsgdiv = '<div data-role="popup" id="showmsg" data-theme="b" class="ui-content" style="filter:alpha(Opacity=95);-moz-opacity:0.9;opacity: 0.9;"><p id="showcontent" style="padding-left: 25px;padding-right: 25px;padding-top: 15px;padding-bottom: 15px;font-size: 15px;">' + msg + '</p></div>';
		$popup = $(showmsgdiv);
	} else {
		$popup = $("#showmsg");
		$("#showcontent").html(msg);
	}
	$popup.popup({
		history: false
	});
	$popup.popup();
	$popup.popup('open');
	if(!(typeof(timeout) == "number" && timeout > 0)) {
		timeout = 2000;
	}
	var msgshow = setTimeout(function() {
		$popup.popup('close');
	}, timeout);
}

//显示加载器  
function showLoader() {  
    //显示加载器.for jQuery Mobile 1.4.5
    $.mobile.loading('show', {
        text: '加载中...', //加载器中显示的文字  
        textVisible: false, //是否显示文字  
        theme: 'a',        //加载器主题样式a-e  
        textonly: false,   //是否只显示文字  
        html: ""           //要显示的html内容，如图片等  
    });
}

//隐藏加载器
function hideLoader(c) {
	if(typeof c== "undefined" || c <= 0){
		$.mobile.loading("hide");
	}
}

function initPage(arg) {
	console.log("结果页面id：" + arg);
	var jsonstr = sessionStorage.getItem($('#' + arg + ' #storeKey').val());
	console.log("缓存数据：" + jsonstr);
	if(jsonstr) {
		if(jsonstr == null){
			$('.cx-no-data').removeClass("hidden");
			$('.cx-mid').remove();
			$('#topay').hide();
			return false;
		}
		var data = $.parseJSON(jsonstr);
		console.log("缓存数据对象：" + data);
		var displayType = $('#' + arg + ' #displayType').val();
		console.log("展示类型：" + displayType);
		if(!data || $.isEmptyObject(data)) {
			$('.cx-no-data').removeClass("hidden");
			$('.cx-mid').remove();
			$('#topay').hide();
			return false;
		}
		if(displayType == 1) {
			if(isArray(data) && data.length > 0) {
				for(var key in data[0]) {
					console.log(key + ':' + data[0][key]);
					var _id = $("#" + arg + " #" + toLowerCase(key));
					_id.html(dict(_id, data[0][key]));
				}
			} else {
				for(var key in data) {
					console.log(key + ':' + data[key]);
					var _id = $("#" + arg + " #" + toLowerCase(key));
					_id.html(dict(_id, data[key]));
				}
			}
		} else if(displayType == 2) {
			$("#" + arg + " #defined-ul").empty();
			var content = "";
			for(var i = 0, l = data.length; i < l; i++) {
				for(var key in data[i]) {
					console.log(key + ':' + data[i][key]);
					var _id = $("#" + arg + " #copy-li #" + toLowerCase(key));
					_id.html(dict(_id, data[i][key]));
				}
				content += $("#" + arg + " #copy-ul").html();
			}
			$("#" + arg + " #defined-ul").append(content)
		} else if(displayType == 3) {

		}
	} else {
		$('.cx-no-data').removeClass("hidden");
		$('.cx-mid').remove();
		$('#topay').hide();
		return false;
	}
}

function dict(_id, val) {
	if(_id.data("dict")) {
		var data = _id.data("dict");
		return data[val];
	} else {
		return val;
	}
}

function isArray(o) {
	return Object.prototype.toString.call(o) == '[object Array]';
}

function toLowerCase(v) {
	if(!isEmpty(v) && v) {
		return v.toLocaleLowerCase();
	}
	return v;
}

function isEmpty(obj) {
	if(typeof obj == "undefined" || obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}

function isMobile(value){
	var length = value.length;
	return length == 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/.test(value);
}